# Allow the user to toggle between static/shared builds
option(CMAKEPORTS_BUILD_SHARED OFF)
if(NOT DEFINED BUILD_SHARED_LIBS)
    set(BUILD_SHARED_LIBS ${CMAKEPORTS_BUILD_SHARED})
endif()

set(CMP_PORTS zlib png jpeg freetype glut lua)

foreach(port ${CMP_PORTS})
    option(BUILD_${port} "Enable building of ${port}" ON)
    if(BUILD_${port})
        # add the port
        add_subdirectory(${port})
    endif()
endforeach()

#
# NOTE:
# The remainder of this file is only relevant if CMAKEPORTS_ASSEMBLE
# is true.  If you are not a CMakePorts maintainer, you can safely ignore
# all of this.
#
if(NOT CMAKEPORTS_ASSEMBLE)
    return()
endif()

# 
# CMakePorts should define the following variables as needed and
# add calls to the appropriate functions (see below).
#
# foo_tarball   => The source tarball file to untar
# foo_directory => The name of the directory the tarball normally creates
# foo_patches   => A list of patch files to apply to the untar'd source tree
#

#
# CMP_standard_patches
#
# Apply the list of patches in ${_name}_patches to ${_name}_directory (-p1)
#
function(CMP_standard_patches _name OUT_STAMPS)
    set(directory ${${_name}_directory})
    set(patches   ${${_name}_patches})
    if(NOT directory)
        message(FATAL_ERROR "ERROR: <pkg>_directory must be defined")
    endif()
    if(NOT patches)
        message(FATAL_ERROR "ERROR: <pkg>_patches list must be defined")
    endif()

    foreach(patch ${${_name}_patches})
        get_filename_component(patch_no_ext ${patch} NAME_WE)
        set(STAMP_FILE ${CMAKE_BINARY_DIR}/${_name}-patch-${patch_no_ext}.stamp)
        file(TO_NATIVE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/${_name}/${patch} patch_full)
        file(TO_NATIVE_PATH ${PATCH_PROGRAM} PATCH_PROGRAM)
        if(WIN32)
            set(PATCH_COMMAND_LINE "${PATCH_PROGRAM}" -p1 --binary -i "${patch_full}")
        else()
            set(PATCH_COMMAND_LINE "${PATCH_PROGRAM}" -p1 -i "${patch_full}")
        endif()

        add_custom_command(OUTPUT ${STAMP_FILE}
                COMMAND ${PATCH_COMMAND_LINE}
                COMMAND ${CMAKE_COMMAND} -E touch ${STAMP_FILE}
                COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt
                COMMENT "Applying patch ${patch} to ${_name} using command:   ${PATCH_COMMAND_LINE}"
                WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${_name}/${${_name}_directory})
        set(${OUT_STAMPS} ${${OUT_STAMPS}} ${STAMP_FILE})
    endforeach()
    set(${OUT_STAMPS} ${${OUT_STAMPS}} PARENT_SCOPE)
endfunction()

#
# CMP_standard_untar
#
# Based entirely off of the ${_name} argument untars a
# specified tarball in a specified directory only if
# the directory doesn't exist yet.
#
# ${_name}           => name of the CMakePort
# ${_name}_tarball   => tarball filename
# ${_name}_directory => directory name to untar to
#
function(CMP_standard_untar _name OUT_STAMPS)
    set(tarball   ${${_name}_tarball})
    set(directory ${${_name}_directory})
    if(NOT tarball)
        message(FATAL_ERROR "ERROR: <pkg>_tarball must be defined")
    endif()
    if(NOT directory)
        message(FATAL_ERROR "ERROR: <pkg>_directory must be defined")
    endif()

    add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/${_name}-untar.stamp
        COMMAND ${CMAKE_COMMAND}
        -Dprojdir=${CMAKE_SOURCE_DIR}
        -Dfilename=${CMAKE_CURRENT_SOURCE_DIR}/${_name}/${${_name}_tarball}
        -Ddirectory=${CMAKE_CURRENT_SOURCE_DIR}/${_name}/${${_name}_directory}
        -P ${CMAKE_SOURCE_DIR}/UntarAndMakeOrigIfNeeded.cmake
        COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_BINARY_DIR}/${_name}-untar.stamp
        COMMENT "Seeing if we should untar ${${_name}_tarball}"
        DEPENDS ${_name}/${${_name}_tarball}
        )
     set(${OUT_STAMPS} ${${OUT_STAMPS}}
         ${CMAKE_BINARY_DIR}/${_name}-untar.stamp PARENT_SCOPE)
endfunction()

#
# CMP_standard_download
#
# Downloads a specified file from a URL
#
# ${_name}           => name of the CMakePort
# ${_name}_url       => The URL to use
# ${_name}_tarball   => tarball filename the URL should save the file as
#                       (should be same as source filename on server)
#
function(CMP_standard_download _name)
    set(tarball   ${${_name}_tarball})
    set(url       ${${_name}_url})
    if(NOT tarball)
        message(FATAL_ERROR "ERROR: <pkg>_tarball must be defined")
    endif()
    if(NOT url)
        message(FATAL_ERROR "ERROR: <pkg>_url must be defined")
    endif()

    if(NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${_name}/${tarball})
        message(STATUS "Downloading ${url} to ${_name}/${tarball}...")
        if(WGET_PROGRAM)
        	execute_process(
        		COMMAND ${WGET_PROGRAM} -O ${CMAKE_CURRENT_SOURCE_DIR}/${_name}/${tarball} ${url}
        		WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${_name}
        		OUTPUT_VARIABLE download_log
        		ERROR_VARIABLE download_log
        		RESULT_VARIABLE error
        	)
        	message(STATUS "   Using wget result  = ${error}")
        	message(STATUS "   wget log = ${download_log}")
        else(WGET_PROGRAM)			
        	file(DOWNLOAD ${url} ${CMAKE_CURRENT_SOURCE_DIR}/${_name}/${tarball}
            STATUS download_status LOG download_log)
        	message(STATUS "   Download_status = ${download_status}")
        	#show the download log.... remove if downloading is stable or too big
        	message(STATUS "   Download_log = ${download_log}")
        	list(GET download_status 0 error)
        endif(WGET_PROGRAM)
    endif()
endfunction()

foreach(port ${CMP_PORTS})
    if(${port}_directory)
        CMP_standard_download(${port})
        CMP_standard_untar(${port}   UNTAR_STAMPS)
        CMP_standard_patches(${port} PATCH_STAMPS)
    endif()
endforeach()

# Create the untar, and patch rules
add_custom_target(untar DEPENDS ${UNTAR_STAMPS})
add_custom_target(patch DEPENDS ${PATCH_STAMPS})
add_dependencies(patch untar)

add_custom_target(nuke)
foreach(port ${CMP_PORTS})
    if(${port}_directory)
    
        # Build up the patch stamps, we're going to want to delete them too.
        set(patch_stamps)
        foreach(patch ${${port}_patches})
            get_filename_component(patch_no_ext ${patch} NAME_WE)
            set(patch_stamps ${patch_stamps} ${CMAKE_BINARY_DIR}/${port}-patch-${patch_no_ext}.stamp)
        endforeach()

        add_custom_command(TARGET nuke
            COMMAND ${CMAKE_COMMAND} -E remove ${patch_stamps}
            COMMAND ${CMAKE_COMMAND} -E remove ${CMAKE_BINARY_DIR}/${port}-untar.stamp
            COMMAND ${CMAKE_COMMAND} -E remove_directory "${CMAKE_CURRENT_SOURCE_DIR}/${port}/${${port}_directory}"
            COMMAND ${CMAKE_COMMAND} -E remove_directory "${CMAKE_CURRENT_SOURCE_DIR}/${port}/${${port}_directory}.orig"
            )
    endif()
endforeach()

# Add a custom rule for preparation
add_custom_target(prep)
add_dependencies(prep untar)
add_dependencies(prep patch)
